package com.cheyunkeji.er.activity.fast_evaluate;

import android.Manifest;
import android.content.Intent;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cheyun.netsalev3.R;
import com.cheyunkeji.er.Constants;
import com.cheyun.netsalev3.MyApplication;
import com.cheyunkeji.er.MyFragmentManager;
import com.cheyunkeji.er.adapter.MyFragmentPagerAdapter;
import com.cheyunkeji.er.app.PushMsgManager;
import com.cheyunkeji.er.app.UserInfoManager;
import com.cheyunkeji.er.base.BaseActivity;
import com.cheyunkeji.er.bean.fast_evaluate.CarModel;
import com.cheyunkeji.er.fragment.fast_evaluate.FastEvaluateFragment;
import com.cheyunkeji.er.fragment.fast_evaluate.FastEvaluateMineFragment;
import com.cheyunkeji.er.fragment.fast_evaluate.FastEvaluatePrevFragment;
import com.cheyunkeji.er.utils.ChannelInfoUtil;
import com.cheyunkeji.er.utils.StringUtils;
import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;

import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import butterknife.BindView;
import butterknife.ButterKnife;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
import q.rorbin.badgeview.Badge;
import q.rorbin.badgeview.QBadgeView;

import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;

public class FastEvaluateActivity extends BaseActivity {

    private static final String TAG = FastEvaluateActivity.class.getSimpleName();

    @BindView(R.id.vp_frags)
    ViewPager vpFrags;
    @BindView(R.id.tl_bottom_selector)
    TabLayout tlBottomSelector;
    @BindView(R.id.iv_close)
    ImageView iv_close;

    private ArrayList<String> titleList;
    private ArrayList<Fragment> fragList;
    private MyFragmentPagerAdapter adapter;

    private onCarModelSelectedListener carModelSelectedListener;

    //   通过选择页面选中好的车型对象，从车型选择界面传递而来
    private CarModel selectedCarModel;
    private Badge mineBadge ;

//    private int[] imgIds = {R.drawable.fast_evaluate_icon_selector,R.drawable.fast_prev_evaluate_icon_selector, R.drawable.fast_evaluate_mine_selector};
private int[] imgIds = {R.drawable.fast_evaluate_icon_selector,R.drawable.fast_evaluate_mine_selector};
    private static final int REQUEST_NECESSARY_PMS_CODE = 0X110;
    String[] perms = {Manifest.permission.CAMERA, ACCESS_FINE_LOCATION, WRITE_EXTERNAL_STORAGE};//权限列表

    @Override
    protected void init() {
        setContentView(R.layout.er_activity_fast_evaluate);
        requestNecessaryPms();
        ButterKnife.bind(this);
    }

    @AfterPermissionGranted(REQUEST_NECESSARY_PMS_CODE)
    private void requestNecessaryPms() {
        if (EasyPermissions.hasPermissions(this, perms)) {
        } else {
            // Do not have permissions, request them now
//            EasyPermissions.requestPermissions(this, getString(R.string.request_necessary_pms),
//                    REQUEST_NECESSARY_PMS_CODE, perms);
            EasyPermissions.requestPermissions(this, "需要获取位置，拍照，存储权限",
                    REQUEST_NECESSARY_PMS_CODE, perms);
        }
    }

    @Override
    protected void initView() {
        titleList = new ArrayList<>();
        fragList = new ArrayList<>();
        titleList.add("快速估价");
//        titleList.add("预估");
        titleList.add("我的");
        mineBadge = new QBadgeView(this);

        fragList.add(MyFragmentManager.getInstance().getFrag(FastEvaluateFragment.class));
//        fragList.add(MyFragmentManager.getInstance().getFrag(FastEvaluatePrevFragment.class));
        fragList.add(MyFragmentManager.getInstance().getFrag(FastEvaluateMineFragment.class));

        adapter = new MyFragmentPagerAdapter(getSupportFragmentManager(), titleList, fragList);
        vpFrags.setAdapter(adapter);
        tlBottomSelector.setupWithViewPager(vpFrags);

//        设置Tab样式
        for (int i = 0; i < tlBottomSelector.getTabCount(); i++) {
            TabLayout.Tab tab = tlBottomSelector.getTabAt(i);
            if (tab != null) {
                View specView = LayoutInflater.from(this).inflate(R.layout.er_indicator, null);
                ImageView ivHome = (ImageView) specView.findViewById(R.id.spec_iv);
                TextView tvHome = (TextView) specView.findViewById(R.id.spec_tv);
                RelativeLayout rlImage = (RelativeLayout) specView.findViewById(R.id.rl_iv);

                tvHome.setText(titleList.get(i));
                tvHome.setTextColor(getResources().getColorStateList(R.color.text_blue_gray));
                ivHome.setBackgroundResource(imgIds[i]);
                tab.setCustomView(specView);

                if (i == 1) {
                    mineBadge.bindTarget(rlImage).setBadgeGravity(Gravity.TOP | Gravity.END).setShowShadow(false) ;
                }
            }
        }
        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        String from = intent.getStringExtra("from");

        setIntent(intent);
        notifyCarBrandSelected(from);
    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshBottomMsgCount();
    }

    public void notifyCarBrandSelected(String from) {
        Object s = getIntent().getSerializableExtra(Constants.SELECTEDCAR_MODEL_OBJECT);
        String d = getIntent().getStringExtra("aaaa");
        if (null != getIntent() && getIntent().getSerializableExtra(Constants.SELECTEDCAR_MODEL_OBJECT) instanceof CarModel) {
            selectedCarModel = (CarModel) getIntent().getSerializableExtra(Constants.SELECTEDCAR_MODEL_OBJECT);
//            setCarModelSelectedListener((FastEvaluateFragment) fragList.get(0));
//          跳转多个页面，获取选中的车型数据并最终返回FastEvaluateActivity时，第一次创建的FastEvaluateFragment可能被销毁掉了，
//          如果一旦销毁，需要显示来自接口回调的数据的控件就会报空指针，所以一定要通过Fragment管理器来获取当前唯一的Fragment
            if (StringUtils.isEmpty(from)) {
                setCarModelSelectedListener((onCarModelSelectedListener) MyFragmentManager.getInstance().getFrag(FastEvaluateFragment.class));
            } else {
                setCarModelSelectedListener((onCarModelSelectedListener) MyFragmentManager.getInstance().getFrag(FastEvaluatePrevFragment.class));
            }
//               通过回调改变Fragment车型一栏数据
            carModelSelectedListener.carModelSelected(selectedCarModel);
//          Toast.makeText(this, "notifyCarBrandSelected", Toast.LENGTH_SHORT).show();
            setIntent(null);
        }
    }

    /**
     * 重写onNewIntent方法，调用setIntent方法，每次Activity从后台切换到前台时，将最新的Intent赋值给缓存Intent，
     * 不然Activity每次从后台切换到前台时获取到的是Activity创建时缓存的Intent
     */
//    @Override
//    protected void onNewIntent(Intent intent) {
//        setIntent(intent);
//        super.onNewIntent(intent);
//    }

    public void setCarModelSelectedListener(onCarModelSelectedListener listener) {
        this.carModelSelectedListener = listener;
    }


    /**
     * 车型选择完毕的回调监听
     */
    public interface onCarModelSelectedListener {
        void carModelSelected(CarModel carModel);
    }


    public void refreshBottomMsgCount() {
        PushMsgManager pushMsgManager = PushMsgManager.getInstance(MyApplication.getInstance(), ChannelInfoUtil.getCurrentChannelInfo().getChannel() + UserInfoManager.getInstance(this).getAccount());
        int msgCount = pushMsgManager.getMsgCount(PushMsgManager.MSG_TYPE_ZHANNEIXIN);
        if (msgCount > 0) {
//               不显示消息记录条数，只显示圆点
            mineBadge.setBadgeNumber(-1);
        } else {
            mineBadge.setBadgeNumber(0);
        }
    }

}
